package ferp.android.views;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import ferp.android.GUI;
import ferp.core.card.Card;
import ferp.core.game.Game;
import ferp.core.game.Settings;
import ferp.core.game.Trick;

/**
 * User: olegs
 * Date: 10/11/12 10:31 PM
 */
public class LastTrickView extends ViewGroup
{
  public LastTrickView(Context context)
  {
    this(context, null);
  }

  public LastTrickView(Context context, AttributeSet attrs)
  {
    super(context, attrs);

    for (int i = 0; i < Game.PLAYERS + 1; ++i)
    {
      cv[i] = new CardView(context, null);
      cv[i].setVisibility(INVISIBLE);
      cv[i].setEnabled(false);

      addView(cv[i]);
    }
  }

  public void show(Settings settings, int trick)
  {
    // talon card (if played) is always on bottom
    Card talon = Trick.talon(trick);

    if (talon == null)
      cv[3].setVisibility(GONE);
    else
      showCard(talon, 3);

    // show players cards by they turn
    for (int i = 0; i < Game.PLAYERS; ++i)
    {
      Card card = Trick.card(trick, i);
      byte player = Trick.owner(trick, i);

      showCard(card, player);
    }
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
  {
    setMeasuredDimension(Math.round(CardView.WIDTH * 1.5f), Math.round(CardView.HEIGHT * 1.5f));
  }

  @Override
  protected void onLayout(boolean changed, int l, int t, int r, int b)
  {
    int shift = 0;
    int y = GUI.center(CardView.HEIGHT, 0, getHeight());

    if (cv[3].getVisibility() == GONE)
      shift = y;
    else
      cv[3].layout(GUI.center(CardView.WIDTH, 0, getWidth()), 0);

    cv[0].layout(GUI.center(CardView.WIDTH, 0, getWidth()), getHeight() - CardView.HEIGHT - shift);
    cv[1].layout(0, y - shift);
    cv[2].layout(getWidth() - CardView.WIDTH, y - shift);
  }

  private void showCard(Card card, int player)
  {
    CardView v = cv[player];

    v.set(card, true);
    v.bringToFront();

    v.setVisibility(VISIBLE);
  }

  private final CardView[] cv = new CardView[Game.PLAYERS + 1];
}
